package com.starter.home.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.starter.home.dao.FriendsDao;
import com.starter.home.dao.UserDao;
import com.starter.home.domain.entity.Friends;
import com.starter.home.domain.entity.User;
import com.starter.home.exception.UserException;
import com.starter.home.service.ILoginLogService;
import com.starter.home.service.IUserService;
import com.starter.home.util.CommonParam;
import com.starter.home.util.PageUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author
 * @since 2020-04-29
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements IUserService {

    @Autowired
    private FriendsDao friendsDao;
    @Autowired
    private ILoginLogService loginLogService;
    @Override
    public User toLogin(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account",user.getAccount());
        User user1 = baseMapper.selectOne(queryWrapper);
        if (Objects.isNull(user1)){
            throw new UserException("用户不存在！");
        }
        if (!user1.getStatus()){
            throw new UserException("你已经被锁定!请联系管理员");
        }
        if (!StringUtils.equals(user.getPassword(),user1.getPassword())){
            throw new UserException("密码不正确！");
        }
        loginLogService.saveUserLogin(user1);
        return user1;

    }

    @Override
    public void changeStatus(Integer id, Boolean status) {
        User user = baseMapper.selectById(id);
        user.setStatus(status);
        int i = baseMapper.updateById(user);
        if (i <= 0){
            throw new UserException("更改用户异常，请稍后重试......");
        }
    }

    @Override
    public PageUtil getUserList(CommonParam commonParam, Integer userId) {
        QueryWrapper<User> queryWrapper = initQueryWrapper(commonParam);
        Set<Integer> idList = this.getConnectUserIds(userId);
        queryWrapper.ne("account","admin");
        queryWrapper.notIn("id",idList);
        if (commonParam.getSize() == 0){
            //获取全部的数据
            List<User> list = this.baseMapper.selectList(queryWrapper);
            return new PageUtil(list.size(),0,list);
        }
        //分页查询货物详情
        Page<User> page = new Page<>(commonParam.getPage(),commonParam.getSize());
        queryWrapper.orderByAsc("nick_name");
        Page<User> pageData = this.baseMapper.selectPage(page, queryWrapper);
        return new PageUtil(pageData.getTotal(),pageData.getCurrent(),pageData.getRecords());
    }

    private Set<Integer> getConnectUserIds(Integer userId) {
        QueryWrapper<Friends> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("from_id",userId);
        Set<Integer> collect = friendsDao.selectList(queryWrapper)
                .stream()
                .map(friends -> (Integer)friends.getToId())
                .collect(Collectors.toSet());
        collect.add(userId);
        return collect;
    }

    @Override
    public void deleteById(Integer id) {
        int i = this.baseMapper.deleteById(id);
        if (i <= 0){
            throw new UserException("删除用户失败!");
        }
    }

    @Override
    public void findByAccount(String account) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account",account);
        Optional<User> user = Optional.ofNullable(this.baseMapper.selectOne(queryWrapper));
        if (user.isPresent()){
            throw new UserException("用户已经存在，请换一个用户注册");
        }
    }

    @Override
    public Boolean saveUser(Integer id, String s) {
        User user = this.baseMapper.selectById(id);
        user.setAvatar(s);
        int i = this.baseMapper.updateById(user);
        return i > 0 ? true :false;
    }

    @Override
    public boolean updateUser(User user) {
        User user1 = baseMapper.selectById(user.getId());
        user.setPassword(user1.getPassword());
        int i = baseMapper.updateById(user);
        return i > 0 ? true : false;

    }

    @Override
    public PageUtil getUserAllList(CommonParam commonParam) {
        QueryWrapper<User> queryWrapper = initQueryWrapper(commonParam);
        if (commonParam.getSize() == 0){
            //获取全部的数据
            List<User> list = this.baseMapper.selectList(queryWrapper);
            return new PageUtil(list.size(),0,list);
        }
        //分页查询货物详情
        Page<User> page = new Page<>(commonParam.getPage(),commonParam.getSize());
        queryWrapper.orderByAsc("id");
        Page<User> pageData = this.baseMapper.selectPage(page, queryWrapper);
        return new PageUtil(pageData.getTotal(),pageData.getCurrent(),pageData.getRecords());

    }

    @Override
    public int getAddUserCount(String s) {
        String startTime = s + " 00:00:00";
        String endTime = s + " 23:59:59";
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("create_time",startTime);
        queryWrapper.le("create_time",endTime);
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    public Integer saveList(List<User> result) {
        result.forEach(e -> {
            e.setPassword(e.getAccount()+"123");
            e.setAvatar("https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2274674939,215103357&fm=15&gp=0.jpg");
            e.setStatus(true);
            e.setType(1);
        });
        AtomicInteger i = new AtomicInteger(0);
        for (User user : result) {
            int insert = baseMapper.insert(user);
            if (insert > 0){
                i.incrementAndGet();
            }
        }
        return i.get();
    }

    private QueryWrapper<User> initQueryWrapper(CommonParam commonParam) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(commonParam.getNickName())){
            queryWrapper.like("nick_name",commonParam.getNickName());
        }
        if (StringUtils.isNotBlank(commonParam.getAccount())){
            queryWrapper.like("account",commonParam.getAccount());
        }
        if (Objects.nonNull(commonParam.getGender())){
            queryWrapper.eq("gender",commonParam.getGender());
        }
        if (Objects.nonNull(commonParam.getStatus())){
            queryWrapper.eq("status",commonParam.getStatus());
        }
        return queryWrapper;
    }
}
